$(function() {
    let res = null;
    let usermsg = JSON.parse(sessionStorage.getItem("usermsg"));
    if (usermsg !== null) {
        writeUserMsg();
    }

    function writeUserMsg() {
        $("#username").val(usermsg.username);
        $("#password_u").val(usermsg.password);

    }

    function login() {
        let options = {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            }
        }
        let data = {
            username: $("#username").val(),
            password: $("#password").val(),
        }
        axios.post("http://127.0.0.1:8888/users/login", formatData(data), options)
            .then(response => {
                console.log(formatData(data));
                console.log(response);
                console.log(response.data);
                res = response.data;
                if (res.code === 0) {
                    error(res);
                } else if (res.code === 1) {
                    success(res);
                }
            })
    }

    $("#user_login2").click(() => login());

    function error(res) {
        alert("抱歉登录失败 : " + res.message);
    }

    function success(res) {
        alert("恭喜登陆成功！");
        cookie("Token", res.token);
        cookie("ID", res.user.id);
        cookie("NickName", res.user.nickname);
        location.href = "index.html";
    }
    $('#regester').on('click',()=>{
        location.href='regester.html';
    })
})